package com.sy.controller;

import com.sy.entity.Admin;
import com.sy.utils.CommonUtils;
import com.sy.utils.RandomUtils;
import com.sy.utils.RedisOperations;
import com.sy.vo.AdminVo;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Objects;

import static com.sy.constant.BusinessConstant.*;
import static com.sy.constant.BusinessConstant.USER_SESSION_MAX_AGE;

@RestController
public class AdminController extends BaseController {

    @Autowired
    private RedisOperations redisOperations;


    /**
     * 属性描述: 响应对象
     */
    @Autowired(required = false)
    private HttpServletResponse res;
    @Autowired
    private HttpServletRequest req;


    @RequestMapping(value = "admins/validateCode", method = RequestMethod.POST)
    public void sendValidateCode(@RequestBody AdminVo adminVo) {

        adminService.sendValidateCode(adminVo.getPhone());
    }


    @RequestMapping(value = "admins/loginByName", method = RequestMethod.POST)
    public Admin loginByName(@RequestBody AdminVo adminVo, @CookieValue(value = COOKIE_ADMIN_TOKEN_NAME,defaultValue = "da") String token) {

        Admin admin = adminService.loginByName(adminVo.getAdminName(), adminVo.getPwd());


        if (StringUtils.isBlank(token)|| StringUtils.equals("da",token)) {
            //生成token
            token = RandomUtils.getUuid();
            //写入浏览器
            Cookie cookie = new Cookie(COOKIE_ADMIN_TOKEN_NAME, token);
            cookie.setPath(COOKIE_ROOT_PATH);
            cookie.setMaxAge(USER_SESSION_MAX_AGE);
            //将登录的管理员对象写入Redis中
            res.addCookie(cookie);
            Map<String, String> adminMap = CommonUtils.bean2Map(admin);
            adminMap.entrySet().removeIf(entry -> Objects.isNull(entry.getValue()));
            String redisAdminKey = REDIS_ADMIN_KEY_PREFIX + token;
            redisOperations.hmset(redisAdminKey, adminMap);
            redisOperations.expire(redisAdminKey, USER_SESSION_MAX_AGE);
        }

        return admin;
    }

    @RequestMapping(value = "admins/loginByPhone", method = RequestMethod.POST)
    public Admin loginByPhone(@RequestBody AdminVo adminVo, @CookieValue(value = COOKIE_ADMIN_TOKEN_NAME,defaultValue = "da") String token) {

        Admin admin = adminService.loginByPhone(adminVo.getPhone(), adminVo.getCode());


        if (StringUtils.isBlank(token)||StringUtils.equals("da",token) ) {
            //生成token
            token = RandomUtils.getUuid();
            //写入浏览器
            Cookie cookie = new Cookie(COOKIE_ADMIN_TOKEN_NAME, token);
            cookie.setPath(COOKIE_ROOT_PATH);
            cookie.setMaxAge(USER_SESSION_MAX_AGE);
            //将登录的管理员对象写入Redis中
            res.addCookie(cookie);
            Map<String, String> adminMap = CommonUtils.bean2Map(admin);
            adminMap.entrySet().removeIf(entry -> Objects.isNull(entry.getValue()));
            String redisAdminKey = REDIS_ADMIN_KEY_PREFIX + token;
            redisOperations.hmset(redisAdminKey, adminMap);
            redisOperations.expire(redisAdminKey, USER_SESSION_MAX_AGE);
        }

        return admin;
    }

    @RequestMapping(value = "admins/loginAdmin", method = RequestMethod.GET)
    public Admin getLoginAdmin() {
        String token = null;
        Cookie[] cookies = req.getCookies();
        if (!ArrayUtils.isEmpty(cookies)) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(COOKIE_ADMIN_TOKEN_NAME)) {
                    token = cookie.getValue();
                }
            }
        }
        if (StringUtils.isNotBlank(token)) {
            String redisAdminKey = REDIS_ADMIN_KEY_PREFIX + token;
            if (redisOperations.exists(redisAdminKey)) {
                Map<String, String> redisAdminMap = redisOperations.hgetall(redisAdminKey);
                Admin admin = CommonUtils.map2Bean(redisAdminMap, Admin.class);
                if (Objects.isNull(admin)) {
                    return null;
                } else {
                    return admin;
                }
            }
        }
        return null;

    }

    @RequestMapping(value = "admins/logout", method = RequestMethod.DELETE)
    public boolean logout(@CookieValue(COOKIE_ADMIN_TOKEN_NAME) String token) {
        //或者Cookie中的token
//        String token = getCookie(COOKIE_USER_TOKEN_NAME);
        if (StringUtils.isNotBlank(token)) {
            //删除Cookie
            Cookie[] cookies = req.getCookies();
            if (!Objects.isNull(cookies)) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals(COOKIE_ADMIN_TOKEN_NAME)) {
                        cookie.setPath(COOKIE_ROOT_PATH);
                        cookie.setMaxAge(COOKIE_MIN_AGE);
                        res.addCookie(cookie);
                    }
                }
            }
            //删除Redis中对应key
            String redisAdminKey = REDIS_ADMIN_KEY_PREFIX + token;
            return redisOperations.del(redisAdminKey);
        }
        return false;
    }
}
